/**
 * HTTP客户端性能对比测试
 *
 * 对比原生HttpSession和基于undici的HttpSessionV2的性能差异
 *
 * 使用方法：
 *   node app/scripts/test-http-performance.mjs [count] [--undici|--native]
 */

import { spawn } from 'node:child_process'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..', '..')
const appRoot = join(projectRoot, 'app')
const testScript = join(appRoot, 'scripts', 'test-http-performance.ts')

// 解析参数
const argv = process.argv.slice(2)
const count = argv[0] ? Number.parseInt(argv[0], 10) : 3
const mode = argv.includes('--undici') ? 'undici' : argv.includes('--native') ? 'native' : 'both'
const noProxy = argv.includes('--no-proxy')
// 支持 --concurrency N / --concurrency=N / -c N
function parseConcurrencyArg(args) {
  const eq = args.find(a => a.startsWith('--concurrency='))
  if (eq) {
    const v = Number.parseInt(eq.split('=')[1] || '1', 10)
    if (!Number.isNaN(v) && v > 0)
      return v
  }
  const idx = args.findIndex(a => a === '--concurrency' || a === '-c')
  if (idx >= 0 && args[idx + 1]) {
    const v = Number.parseInt(args[idx + 1], 10)
    if (!Number.isNaN(v) && v > 0)
      return v
  }
  return 1
}
const concurrency = parseConcurrencyArg(argv)

console.log('='.repeat(80))
console.log('HTTP客户端性能对比测试')
console.log('='.repeat(80))
console.log(`测试数量: ${count}`)
console.log(`测试模式: ${mode === 'both' ? '对比模式（先native后undici）' : mode}`)
console.log(`并发: ${concurrency}`)
if (noProxy) {
  console.log('⚠️  已禁用代理，进行公平对比')
}
console.log('='.repeat(80))
console.log()

const testArgs = [
  'tsx',
  '--tsconfig',
  join(appRoot, 'tsconfig.node.json'),
  testScript,
  String(count),
  mode,
  ...(noProxy ? ['--no-proxy'] : []),
  ...(concurrency > 1 ? ['--concurrency', String(concurrency)] : []),
]

const proc = spawn('npx', testArgs, {
  cwd: appRoot,
  stdio: 'inherit',
  shell: true,
  windowsVerbatimArguments: false,
})

proc.on('close', (code) => {
  process.exit(code || 0)
})

proc.on('error', (error) => {
  console.error('[ERROR] 执行测试失败:', error)
  console.error('\n提示: 请确保已安装必要的依赖:')
  console.error('  pnpm install')
  process.exit(1)
})
